package com.appstore;

import com.appstore.common.AliOSSUtils;
//import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.testng.annotations.Test;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@SpringBootTest
public class RuoYiApplicationTest {
    AliOSSUtils ossUtils = new AliOSSUtils();

    private FileItem getMultipartFile(File file, String fieldName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
        int bytesRead = 0;
        int len = 8192;
        byte[] buffer = new byte[len];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, len)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

    @Test
    public void testUpload() throws Exception {
        String imagePath = "D:\\System\\Download\\profile.png";
        File file = new File(imagePath);
        FileItem fileItem = getMultipartFile(file, "test");
        System.out.println("fileItem is " + fileItem);
        MultipartFile multipartFile = new CommonsMultipartFile((org.apache.commons.fileupload.FileItem) fileItem);
        System.out.println("multipartFile is " + multipartFile);

        // 测试单张图片上传
        String url = ossUtils.upload(multipartFile, "images");
        System.out.println("返回的url为: " + url);

        // 测试多张图片上传
//        List<MultipartFile> fileList = new ArrayList();
//        fileList.add(multipartFile);
//        fileList.add(multipartFile);
//        fileList.add(multipartFile);
//
//        List<String> classList = new ArrayList<>();
//        classList.add("images");
//        classList.add("avatar");
//        classList.add("images");
//
//        List<String> urlList = ossUtils.uploadFiles(fileList, classList);
//        System.out.println("返回的urlList 为："+ urlList);
    }

}
